package com.avic.rong.userOrder.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.userOrder.api.AddCommentApi;
import com.avic.rong.userOrder.api.GetCommentApi;
import com.avic.rong.userOrder.bean.AllOrderListBean;
import com.avic.rong.userOrder.bean.DetailsEvaluateBean;
import com.avic.rong.userOrder.bean.GetCommentBean;
import com.avic.rong.userOrder.event.InformUpdate;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.GlideUtils;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.AppUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class OrderEvaluateActivity extends BaseActivity {


    @BindView(R.id.iv_goods_pic)
    ImageView iv_goods_pic;
    @BindView(R.id.tv_goods_titls)
    TextView tvGoodsTitls;
    @BindView(R.id.ll_goods_name)
    LinearLayout ll_goods_name;
    @BindView(R.id.tv_goods_subtitle)
    TextView tvGoodsSubtitle;
    @BindView(R.id.et_evaluate)
    EditText et_evaluate;
    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;
    @BindView(R.id.tv_goods_type)
    TextView tv_goods_type;
    @BindView(R.id.tv_goods_tel)
    TextView tv_goods_tel;
    @BindView(R.id.ll_pic_tag)
    LinearLayout ll_pic_tag;
    @BindView(R.id.tv_status)
    TextView tv_status;

    private DetailsEvaluateBean faHuoBean;
    private DetailsEvaluateBean weifaHuoBean;


    private AllOrderListBean.OrderListBean.ItemsViewBean itemsViewBean;

    private AllOrderListBean.OrderListBean orderListBean;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_order_evaluate;
    }

    @Override
    protected void initView() {
        tvTitle.setText("发表评价");
        tvRight.setText("发布");
        tvRight.setTextColor(getResources().getColor(R.color.white));
        loading_layout.setStatus(LoadingLayout.SUCCESS);
        itemsViewBean = (AllOrderListBean.OrderListBean.ItemsViewBean) getIntent().getSerializableExtra("goods_order");
        orderListBean = (AllOrderListBean.OrderListBean) getIntent().getSerializableExtra("good_bean");
        faHuoBean = (DetailsEvaluateBean) getIntent().getSerializableExtra("faHuoBean");
        weifaHuoBean = (DetailsEvaluateBean) getIntent().getSerializableExtra("weifaHuoBean");
        if (itemsViewBean != null || faHuoBean != null || weifaHuoBean != null) {
            if (itemsViewBean != null) {
                if (orderListBean == null) return;

                if (orderListBean.getOrderType() == 4) {
                    if (!TextUtils.isEmpty(itemsViewBean.getGoodsImg())) {
                        if (itemsViewBean.getGoodsImg().contains("rongrong.")) {
                            GlideUtils.loaderHanldeRoundImage(context, itemsViewBean.getGoodsImg(), iv_goods_pic, 10);
                        } else {
                            GlideUtils.loaderHanldeRoundImage(context, orderListBean.getBiaoZhunImg() + itemsViewBean.getGoodsImg(), iv_goods_pic, 10);
                        }
                        iv_goods_pic.setVisibility(View.VISIBLE);
                        ll_pic_tag.setVisibility(View.GONE);
                    } else {
                        String keywords = itemsViewBean.getKeywords();
                        String catName = itemsViewBean.getCatName();
                        tv_goods_tel.setText(keywords);
                        tv_goods_type.setText(catName);
                        ll_pic_tag.setVisibility(View.VISIBLE);
                        iv_goods_pic.setVisibility(View.VISIBLE);
//                    Glide.with(context).load(R.mipmap.common_bg).into(iv_goods_pic);
                        GlideUtils.loaderHanldeRoundImageResource(context, R.mipmap.common_bg, iv_goods_pic, 10);
                    }
                } else {
                    if (!TextUtils.isEmpty(itemsViewBean.getGoodsImg())) {
                        GlideUtils.loaderHanldeRoundImage(context, itemsViewBean.getGoodsImg(), iv_goods_pic, 10);
                        iv_goods_pic.setVisibility(View.VISIBLE);
                        ll_pic_tag.setVisibility(View.GONE);
                    } else {
                        //默认图
//                GlideUtils.loaderImage(context, R.mipmap.common_bg, iv_goods_pic);
                        String keywords = itemsViewBean.getKeywords();
                        String catName = itemsViewBean.getCatName();
                        tv_goods_tel.setText(keywords);
                        tv_goods_type.setText(catName);
                        GlideUtils.loaderHanldeRoundImageResource(context, R.mipmap.common_bg, iv_goods_pic, 10);
                        iv_goods_pic.setVisibility(View.VISIBLE);
                        ll_pic_tag.setVisibility(View.VISIBLE);
                    }

                }


                tvGoodsTitls.setText(itemsViewBean.getGoodsName());

                if (orderListBean.getOrderType() != 5) {

                    String subtitle = orderSubtitle(itemsViewBean.getSkuName());
                    if (subtitle != null) {
                        tvGoodsSubtitle.setText(subtitle);
                    }
                } else {
                    if (TextUtils.isEmpty(itemsViewBean.getSkuName())) {
                        return;
                    }
                    tvGoodsSubtitle.setText(itemsViewBean.getSkuName());
                }
                if (!TextUtils.isEmpty(itemsViewBean.getAttrShow())) {
                    tv_status.setText(itemsViewBean.getAttrShow());
                    tv_status.setVisibility(View.VISIBLE);
                }


               /* GlideUtils.loaderImage(this, itemsViewBean.getGoodsImg(), ivGoodsPic);
                tvGoodsTitls.setText(itemsViewBean.getGoodsName());


                String subtitle = orderSubtitle(itemsViewBean.getSkuName());
                if (subtitle != null) {
                    tvGoodsSubtitle.setText(subtitle);
                } else {
                    tvGoodsSubtitle.setText(itemsViewBean.getSkuName());
                }*/

            } else if (faHuoBean != null) {
                GlideUtils.loaderImage(this, faHuoBean.getPic(), iv_goods_pic);
                tvGoodsTitls.setText(faHuoBean.getTitle());

                String subtitle = orderSubtitle(faHuoBean.getSubTitle());
                if (subtitle != null) {
                    tvGoodsSubtitle.setText(subtitle);
                } else {
                    tvGoodsSubtitle.setText(faHuoBean.getSubTitle());
                }
            } else if (weifaHuoBean != null) {
                GlideUtils.loaderImage(this, weifaHuoBean.getPic(), iv_goods_pic);
                tvGoodsTitls.setText(weifaHuoBean.getTitle());

                String subtitle = orderSubtitle(weifaHuoBean.getSubTitle());
                if (subtitle != null) {
                    tvGoodsSubtitle.setText(subtitle);
                } else {
                    tvGoodsSubtitle.setText(weifaHuoBean.getSubTitle());
                }
            }

        } else {
            finish();

        }

        //评价回显
        evaluateShow();

    }

    private void evaluateShow() {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            if (itemsViewBean != null) {
                map.put("orderId", itemsViewBean.getOrderId() + "");
                map.put("goodsId", itemsViewBean.getGoodsId() + "");
            } else if (faHuoBean != null) {
                map.put("orderId", faHuoBean.getDetailsID() + "");
            } else if (weifaHuoBean != null) {
                map.put("orderId", weifaHuoBean.getDetailsID() + "");
            }
            map.put("token", getSharedPreferencesUtil().getLogintoken());
            final GetCommentApi getCommentApi = new GetCommentApi(this, simpleOnNextListenerOrderEvaluateShow);
            getCommentApi.setCache(false);
            getCommentApi.setMap(map);

            HttpManager.getInstance().doHttpDeal(getCommentApi);
            loading_layout.setStatus(LoadingLayout.LOADING);
        } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }
    }

    @Override
    protected void addListener() {
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                orderEvaluate();
            }
        });

    }

    private void orderEvaluate() {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            String orderComment = et_evaluate.getText().toString().trim();
            Map<String, String> map = new HashMap<>();
            if (itemsViewBean != null) {
                map.put("orderId", itemsViewBean.getOrderId() + "");
                map.put("goodsId", itemsViewBean.getGoodsId() + "");
            } else if (faHuoBean != null) {
                map.put("orderId", faHuoBean.getDetailsID() + "");
            } else if (weifaHuoBean != null) {
                map.put("orderId", weifaHuoBean.getDetailsID() + "");
            }

            map.put("token", getSharedPreferencesUtil().getLogintoken());
            map.put("comments", orderComment);
            final AddCommentApi addCommentApi = new AddCommentApi(this, simpleOnNextListenerOrderEvaluate);
            addCommentApi.setCache(false);
            addCommentApi.setMap(map);

            HttpManager.getInstance().doHttpDeal(addCommentApi);

            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(addCommentApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });
            loading_layout.setStatus(LoadingLayout.LOADING);
        } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }
    }

    //评价回显
    HttpOnNextListener simpleOnNextListenerOrderEvaluateShow = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(OrderEvaluateActivity.this, subjects.getMsg());
                return;
            }
            loading_layout.setStatus(LoadingLayout.SUCCESS);
            List<GetCommentBean> listData = (List<GetCommentBean>) subjects.getData();
            if (listData != null && listData.size() > 0) {
                String content = listData.get(0).getContent();
                if (TextUtils.isEmpty(content)) return;
                et_evaluate.setText(content);
            }


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };
    //添加评价
    HttpOnNextListener simpleOnNextListenerOrderEvaluate = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(OrderEvaluateActivity.this, subjects.getMsg());
                return;
            }
            loading_layout.setStatus(LoadingLayout.SUCCESS);
            InformUpdate informUpdate = new InformUpdate();
            informUpdate.setEventType(informUpdate.ORDER_COMMENT_INFORM);
            EventBus.getDefault().post(informUpdate);
            finish();

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    private String orderSubtitle(String orderSkuName) {
        JSONArray jsonArray = null;
        String skuName = "";
        try {
            if (TextUtils.isEmpty(orderSkuName)) {
                return null;
            }
            jsonArray = new JSONArray(orderSkuName);
            StringBuffer paramsSb = new StringBuffer("");
            StringBuffer moreParamsb = new StringBuffer("");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                Iterator<String> keys = jsonObject.keys();
                String key = "";
                while (keys.hasNext()) {//遍历JSONObject

                    key = (String) keys.next().toString();

                    if (null != key && !"".equals(key)) {

                        String value = (String) jsonObject.get(key);
                        if (jsonArray.length() > 1) {
//                            skuName = value +"; ";
                            paramsSb.append(value + " ; ");
                        } else {
                            paramsSb.append(value);
                        }


                    }

                }


            }
            if (jsonArray.length() > 1) {
                moreParamsb.append(paramsSb.deleteCharAt(paramsSb.length() - 2));
                return moreParamsb.toString();
            } else {
                return paramsSb.toString();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


}
